<template>
  <div class="qr_code">
    <div id="login_container" />
  </div>
</template>

<script>
import axios from 'axios'
/* eslint-disable */
!(function (window, document) {
  function d(a) {
    var e
    var c = document.createElement('iframe')
    var d = 'https://login.dingtalk.com/login/qrcode.htm?goto=' + a.goto;
    (d += a.style ? '&style=' + encodeURIComponent(a.style) : ''),
      (d += a.href ? '&href=' + a.href : ''),
      (c.src = d),
      (c.frameBorder = '0'),
      (c.allowTransparency = 'true'),
      (c.scrolling = 'no'),
      (c.width = a.width ? a.width + 'px' : '365px'),
      (c.height = a.height ? a.height + 'px' : '400px'),
      (e = document.getElementById(a.id)),
      (e.innerHTML = ''),
      e.appendChild(c)
  }
  window.DDLogin = d
})(window, document)
/* eslint-enable */
export default {
  name: 'DdLogin',
  data() {
    return {
      qrLoginForm: {
        code: ''
      }
    }
  },
  mounted() {
    let code = this.$route.query.code
    this.qrLoginForm.code = code
    if (this.qrLoginForm.code) {
      // 当存在loginTmpCode
      this.requestQrLogin()
    } else {
      this.myQrLogin()
    }
  },
  methods: {
    /* 二维码登录 begin */
    requestQrLogin() {
      const formdata = new FormData()
      formdata.append('grant_type', 'third_code')
      formdata.append('third_code', 'qr_tmp_code:' + this.qrLoginForm.code)
      // 下面发送请求
      // Authorization:  oms:oms_secret
      axios({
        method: 'POST',
        url: '/ly-code-auth-servicer/oauth/token',
        headers: {
          'Content-Type': 'application/json;charset=UTF-8',
          'jx_Authorization': 'Basic b21zOm9tc19zZWNyZXQ='
        },
        data: formdata,
        params: null
      }).then(res => {
        res = res.data
        if (Object.values(res).length) {
          if (res.token_type) {
            // this.$store.commit('SET_TOKEN', res.access_token)
            this.$setLocalItem('jx_access_token', res.access_token)
            this.$setLocalItem('jx_Authorization', 'bearer ' + res.access_token)
            this.$setLocalItem('jx_refresh_token', res.refresh_token)
            this.$setLocalItem('jx_tokenType', res.token_type)
            this.$setLocalItem('jx_nickname', res.nickname)
            this.$setLocalItem('jx_username', res.username)
            this.$setLocalItem('jx_avatar', res.avatar)
            // this.getRoleCode(res.access_token)
            this.getLoginMsg()
            if (res.deptList[0]) {
              this.$setLocalItem('jx_deptId', res.deptList[0].deptId)
              this.$setLocalItem('jx_deptName', res.deptList[0].deptName)
              this.$setLocalItem('jx_deptType', res.deptList[0].deptType)
            }
          }
        }
      }).catch((err) => {
        console.log(err)
        this.$message.error('扫码登录失败，请重新扫码!')
        let timer = setTimeout(() => {
          window.location.href = window.location.origin + '/ly-jx-pcr/#/login'
          clearTimeout(timer)
        }, 2000)
      })
    },
    getLoginMsg() {
      // 获取权限和菜单树
      Promise.all([this.$store.dispatch('jx_ReqUserMenu'), this.$store.dispatch('jx_ReqUserMsg')]).then(response => {
        const myRes = response[0]
        let path = '/permission'
        if (myRes.code == 0) {
          const data = myRes.data
          if (data.length > 0) {
            path = '/homePage'
          }
        }
        const res = response[1]
        if (res) {
          // 存登录信息
          this.$setLocalItem('jx_RoleCode', res.res.authorities)
          this.$setLocalItem('jx_userinfo', res.res.user_id)
          this.$setLocalItem('jx_nickname', res.res.nickname)
          this.$setLocalItem('pageBtn', res.res.authorities.filter(v => v.indexOf('lypc_btn_') > -1))
        }
        this.$goPage({ path: path })
      })
    },
    myQrLogin() {
      var loginParam = {}
      loginParam['appid'] = 'dinglkpq4j06rw14s6fb'// 修改appkey
      loginParam['redirectUri'] = this.$userLoginUrl
      var gotoUrl = encodeURIComponent(`https://oapi.dingtalk.com/connect/oauth2/sns_authorize?appid=${loginParam.appid}&response_type=code&scope=snsapi_login&state=STATE&redirect_uri=${loginParam.redirectUri}`)
      window.DDLogin({
        id: 'login_container',
        goto: gotoUrl,
        style: 'border:none;background-color:#FFFFFF;',
        width: '260',
        height: '290'
      })
      // **width和height不代表二维码的大小，二维码大小是固定的210px210px。
      var hanndleMessage = function(event) {
        const { origin } = event
        if (origin == 'https://login.dingtalk.com') { // 判断是否来自ddLogin扫码事件。
          const { data: loginTmpCode } = event // 拿到loginTmpCode后就可以在这里构造跳转链接进行跳转了
          console.log('loginTmpCode', loginTmpCode)
          // 通过JS获取到loginTmpCode后，需要由你构造并跳转到如下链接：
          // `https://oapi.dingtalk.com/connect/oauth2/sns_authorize?appid=APPID&response_type=code&scope=snsapi_login&state=STATE&redirect_uri=REDIRECT_URI&loginTmpCode=loginTmpCode`
          // 此链接处理成功后，会302跳转到你goto参数指定的redirect_uri，并向url参数中追加临时授权码code及state两个参数。
          const tempUrl = `https://oapi.dingtalk.com/connect/oauth2/sns_authorize?appid=${loginParam.appid}&response_type=code&scope=snsapi_login&state=STATE&redirect_uri=${loginParam.redirectUri}&loginTmpCode=${loginTmpCode}`
          window.location.href = tempUrl
        }
      }
      if (typeof window.addEventListener != 'undefined') {
        window.addEventListener('message', hanndleMessage, false)
      } else if (typeof window.attachEvent != 'undefined') {
        window.attachEvent('onmessage', hanndleMessage)
      }
    },
    paramFromUrl(name) {
      var reg = new RegExp('(^|&|#)' + name + '=([^&]*)(&|$)', 'i')
      var r = window.location.href.replace(/(.*)(\?)(.*)/, '$3').match(reg)
      return r ? r[2] : ''
    },
    // 从地址栏获取loginTmpCode
    getCodeFromParam() {
      this.qrLoginForm.code = this.paramFromUrl('code')
    }
  }
}
</script>

<style lang="scss" scoped>
.qr_code {
  position: relative;
  #login_container {
    overflow: hidden;
  }
}
</style>

